package com.gl.emms.whale.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gl.emms.whale.R;
import com.gl.emms.whale.app.Constant;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.bean.UserData;
import com.gl.emms.whale.util.SDTools;
import com.gl.emms.whale.util.SharePreferenceUtil;
/**用户信息界面类
 * @author ganlinux
 *
 */
public class AccountInfoActivity extends WhaleMonitorActivity implements OnClickListener{
	private ImageView headImage;//头像图片控件
	private TextView userNameText;//用户名控件
	private TextView phoneText;//电话号码控件
	private TextView roomText;//房间号控件
	private TextView cardNumText;//卡号控件
	private TextView lastLoginTimeText;//上次登录时间控件
	private TextView invoiceText;//上次登录时间控件
	
	private SharePreferenceUtil util;//轻量级存储组件

	/* 请求码*/
	private static final int IMAGE_REQUEST_CODE = 0;//图片请求码
	private static final int CAMERA_REQUEST_CODE = 1;//摄像头请求码
	private static final int RESULT_REQUEST_CODE = 2;//请求结果码
	private static final String SD_IMAGE_DIR = "/sdcard/whale/images";//请求结果码
	private static final String SD_IMAGE_FILE = "/sdcard/whale/images/headImage.jpg";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.activity_accountinfo);//设置activity显示界面
		
		initViews();//初始化显示控件
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.TitleBackBtn://返回按钮
			new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_BACK);
			finish();
			break;

		default:
			break;
		}
	}
	
	/**
	 * 初始化显示控件
	 * @time 2014年11月12日上午10:01:24
	 * @return void
	 * @user ganlinux
	 */
	@Override
	public void initViews()
	{
		//设置返回按钮
		Button titleBackBtn = (Button)findViewById(R.id.TitleBackBtn);
		titleBackBtn.setOnClickListener(this);
		//头像
		headImage = (ImageView) findViewById(R.id.personal_head_imageview);
		util = new SharePreferenceUtil(this, Constant.SAVE_USERINFO);//从存储中获得路径
		
		String imageUrl = util.getHeadImageUrl();//得到存储的头像路径
		if (imageUrl.equals("")) {
			//未存储
			headImage.setImageResource(R.drawable.app_panel_friendcard_icon);
		}else
		{
			
			File temp = new File(imageUrl);//自已项目 文件夹  
			if (!temp.exists()) {//路径不存在
				headImage.setImageResource(R.drawable.app_panel_friendcard_icon); 
			}else {//设置路径
				headImage.setImageURI(Uri.parse(imageUrl));
			}
		}

		//获取存储的数据，并显示
		UserData userData = MyApplication.getUserData();
		//用户名
		userNameText = (TextView) findViewById(R.id.username);
		userNameText.setText(userData.getName());

		//手机号
		phoneText = (TextView) findViewById(R.id.phonenum);
		phoneText.setText(userData.getPhone());
		//房间号
		roomText = (TextView) findViewById(R.id.room);
		roomText.setText(userData.getMainroom());
		//卡号
		cardNumText = (TextView) findViewById(R.id.cardnum);
		cardNumText.setText(userData.getCardnum());
		//上次登录时间
		lastLoginTimeText = (TextView) findViewById(R.id.lastlogintime);
		lastLoginTimeText.setText(userData.getLasttime());
		
		
		
		invoiceText = (TextView) findViewById(R.id.invoice_info);
		invoiceText.setText(userData.getInvoice());
	}
	/**
	 * 更换头像
	 * @time 2014年11月12日上午10:05:18
	 * @return void
	 * @param v
	 * @user ganlinux
	 */
	public void change_avatar(View v) {
		CharSequence[] items = { getText(R.string.select_avatar_image), getText(R.string.select_avatar_camera) };
		imageChooseItem(items);//选择头像显示方式
	}
	
	/**
	 * 选择头像显示方式
	 * @time 2014年11月12日上午10:01:35
	 * @return void
	 * @param items
	 * @user ganlinux
	 */
	public void imageChooseItem(CharSequence[] items) {
		AlertDialog imageDialog = new AlertDialog.Builder(this)
		.setTitle(getText(R.string.alert_title))
		.setIcon(android.R.drawable.btn_star)
		.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				// 手机选图
				if (item == 0) {
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery,IMAGE_REQUEST_CODE);
				}
				// 拍照
				else if (item == 1) {
					Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					// 判断存储卡是否可以用，可用进行存储
					if (SDTools.hasSdcard()) {
						intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"faceImage.jpg")));
					}
					startActivityForResult(intentFromCapture,CAMERA_REQUEST_CODE);
				}
			}
		}).create();

		imageDialog.show();
	}

	/**
	 * 更换或验证手机号
	 * @time 2014年11月12日上午10:01:55
	 * @return void
	 * @param v
	 * @user ganlinux
	 */
	public void change_phone(View v) {
		
	}
	/**
	 * 更换发票信息
	 * @time 2014年11月12日上午10:01:55
	 * @return void
	 * @param v
	 * @user ganlinux
	 */
	public void change_invoice(View v) {
		final TextView invoiceTextvView = new EditText(AccountInfoActivity.this);
		new AlertDialog.Builder(AccountInfoActivity.this)  
		.setTitle("请输入发票信息")  
		.setIcon(android.R.drawable.ic_dialog_info)  
		.setView(invoiceTextvView)  
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
        	   invoiceText.setText(invoiceTextvView.getText().toString());
           }
       })
       .setNegativeButton("取消", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       })
		.show();
	}
	//返回结果处理
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				startPhotoZoom(data.getData());//启动图像裁剪
				break;
			case CAMERA_REQUEST_CODE:
				if (SDTools.hasSdcard()) {
					//启动图像裁剪
					startPhotoZoom(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"faceImage.jpg")));
				} else {
					//无存储卡
					showToask(getString(R.string.storage_err));
				}
				break;
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);//把图像显示出来
				}
				break;
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	
	
	/**
	 * 裁剪图片
	 * @time 2014年11月12日上午10:02:20
	 * @return void
	 * @param uri
	 * @user ganlinux
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		intent.putExtra("scale", true);//黑边
		intent.putExtra("scaleUpIfNeeded", true);//黑边
		
		File temp = new File(SD_IMAGE_DIR);//自已项目 文件夹  
		if (!temp.exists()) {  
			temp.mkdir();  
		}  
		File tempFile = new File(SD_IMAGE_FILE);
		intent.putExtra("output", Uri.fromFile(tempFile));  // 专入目标文件
		    
		intent.putExtra("outputFormat", "JPEG"); //输入文件格式 
		
		startActivityForResult(intent, 2);
	}

	
	/**
	 * 保存裁剪之后的图片数据
	 * @time 2014年11月12日上午10:02:51
	 * @return void
	 * @param data
	 * @user ganlinux
	 */
	private void getImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			@SuppressWarnings("deprecation")
			Drawable drawable = new BitmapDrawable(photo);
			headImage.setImageDrawable(drawable);

			File f = new File(Constant.IMAGE_PATH, Constant.IMAGE_NAME);
			util.setHeadImage(f.getAbsolutePath());
			File temp = new File(Constant.IMAGE_PATH);//自已项目 文件夹  
			if (!temp.exists()) {  
				temp.mkdir();  
			}
			try {
				FileOutputStream out = new FileOutputStream(f);
				photo.compress(Bitmap.CompressFormat.PNG, 90, out);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				util.setHeadImage("");//如果存储有误则还原
				e.printStackTrace();
			}
			
		}
	}
}
